from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request


from info import constants
from info.models import News, Category
from info.utils.commons import login_user_data
from info.utils.response_code import RET
from . import index_blu
from info import redis_store


@index_blu.route('/news')
def news():
    """
    获取分类新闻信息:
    1.接收参数(新闻分类id,页码,每页容量)并进行参数验证
    2.根据category_id查询分类新闻信息并且分页
    3.遍历分类信息对象列表,将每一个对象转换成python字典
    4.返回应答
    """
    # 1.接收参数(新闻分类id,页码,每页容量)并进行参数验证
    category_id = request.args.get('cid')
    page = request.args.get('page', 1)  # 如果获取不到page get方法默认返回为1 默认值:1
    per_page = request.args.get('per_page', constants.HOME_PAGE_MAX_NEWS)  # 第二个参数 default为首页单页显示新闻最多数量
    # 验证参数 category_id需要验证  page,per_page可不传 有默认值 无需验证
    if not category_id:
        return jsonify(errno=RET.PARAMERR, errmsg='缺少参数')
    # 这里的参数均为int 格式转化int  不报错就代表参数格式没有错
    try:
        category_id = int(category_id)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 2.根据category_id查询分类新闻信息并且分页
    filters = [News.status == 0]
    if category_id != 1:
        filters.append(News.category_id == category_id)
    try:
        pagination = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(
            page, per_page, False)
        news_li = pagination.items
        total_page = pagination.pages
        current_page = pagination.page
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='获取分类新闻信息失败')

    # 3.遍历分类信息对象列表,将每一个对象转换成python字典
    news_dict_li = []
    for news in news_li:
        news_dict_li.append(news.to_basic_dict())  # to_basic_dict方法在models中用来将新闻对象转化为字典
    # 4.返回应答
    return jsonify(errno=RET.OK, errmsg='ok',
                   news_li=news_dict_li,
                   total_page=total_page,
                   current_page=current_page)


# 使用蓝图对象注册路由
@index_blu.route('/', methods=['get', 'post'])
@login_user_data
def index():
    # 判断用户有没有登陆
    # user_id = session.get('user_id')
    # user = None
    # if user_id:
    #     # 用户已登陆
    #     try:
    #         user = User.query.get(user_id)
    #         user.avatar_url = constants.QINIU_DOMIN_PREFIX + user.avatar_url
    #     except Exception as e:
    #         current_app.logger.error(e)
    user = g.user
    # 获取'点击排行'新闻的信息
    rank_news_li = []
    try:
        rank_news_li = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)

    # 获取首页'新闻分类'的信息
    categories = []
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    return render_template('news/index.html',
                           user=user,
                           rank_news_li=rank_news_li,
                           categories=categories)


@index_blu.route('/favicon.ico')
def get_web_ico():
    """获取网站的图标"""
    return current_app.send_static_file('news/favicon.ico')
